﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Windows;
using ReflectionStudio.Core;
using ReflectionStudio.Core.Database;
using ReflectionStudio.Core.Events;
using INTEX.DataBase;
using System.Linq;

namespace WPFExcelReport
{
    public partial class JLTCAD2ITXData
    {
    
        string Today
        {
            get
            {
                DateTime now = System.DateTime.Now;
                string year = now.Year.ToString();
                string m = now.Month.ToString();
                string day = now.Day.ToString();
                return year + "-" + m + "-" + day;
            }
        }

        public DataSet QueryFINISHINGTECHMASTER()
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            DataSet setTemp = new DataSet();
            DataTable tableLocal = null;
            SqlCommand sql;
            try
            {
                sql = SqlServerDB.CreateCommand();
                sql.CommandText = "select distinct 编号 as FInterID,编号 as FShortCode,名称 as FFinishingTechName,名称 as    FWholeFinishingName,英文名称 as  FComments  from 整理加工";
                setResult = Connect2Proxy(sql);
                if (setResult.Tables.Count > 0)
                {
                    tableLocal = setResult.Tables[0];
                    tableLocal.TableName = "FINISHINGTECHMASTER";
                }
                setReturn.Merge(setResult);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return setReturn;
        }
        private void GetFColor(ref DataSet src)
        {
            if (src.Tables.Count == 0)
                return;
            foreach (DataRow row in src.Tables[0].Rows)
            {
                string cloth = row["FClothNO"].ToString();
                string color = row["FColorNO"].ToString();
                if (!cloth.Contains("-"))
                    continue;
                char sg = '-';
                if (cloth.Contains('/'))
                    sg = '/';
                int nums = cloth.Split(new char[1] { sg}).Count();
                if (nums ==2)
                {
                    row["FColorNO"] = 1;
                    continue;
                }
                int lg = cloth.Length;
                int idx = cloth.LastIndexOf(sg);

                try
                {
                    color = cloth.Substring(idx + 1, lg - idx - 1);
                    cloth = cloth.Substring(0, idx);
                    row["FClothNO"] = cloth;
                    row["FColorNO"] = color;
                }
                catch (Exception ex)
                {
                    Tracer.Error(ex.StackTrace, ex);
                }
            }
        }
        
        public DataSet QueryLogInfor(string FInterID, string FClothNo)
        {
            DataSet SReturn = new DataSet();
            DataSet SResult = new DataSet();
            DataSet STemp = new DataSet();
            DataTable tableLocal = null;
            SqlCommand sql;
            try
            {
                sql = SqlServerDB.CreateCommand();
                EventDispatcher.Instance.RaiseStatus("读取" + FClothNo + "信息", StatusEventType.StopProgress);
                //sql.CommandText = "SELECT rTrim(布号)+rTrim(花号) as FinterID,设计员 as FDesignName, 日期 as FEditDate,布号 as FClothNO, 花号 as FColorNO FROM 规格表 where 日期='" + Today + "'";
                sql.CommandText = "  SELECT  LTRIM(str(max(FInterID),10)) as FINTERID,  max(FDesignName) as FDESIGNNAME"
                + ",convert(varchar(20),max(FEditDate)) as FEDITDATE,l.FClothNO as FCLOTHNO,l.FColorNO as FCOLORNO,l.FClothNO as FCADKEY"
                    + " FROM jinling.dbo.LogInfo l "
                    + "  WHERE FClothNO like '" + FClothNo.Trim() + "%' AND l.FInterID>" + FInterID
                    + " group by FClothNO,FColorNO "
                    + " ORDER BY 1,2";
                SResult = Connect2Proxy(sql);
                if (SResult.Tables.Count > 0)
                {
                    tableLocal = SResult.Tables[0];
                    tableLocal.TableName = "LOGINFO";
                }
                GetFColor(ref SResult);
                SReturn.Merge(SResult);             
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return SReturn;
        }
        public DataSet PrepareCADData(string fKey,string fcloth,string fcolor,string cadkey)
        {
            DataSet SReturn = new DataSet();
            DataSet SResult = new DataSet();
            DataTable tableLocal = null;
            SqlCommand sql;
            bool fail = false;
            try
            {

                sql = SqlServerDB.CreateCommand();
                sql.CommandText = "SELECT ISNULL(品名,'') As FAssortment,M.布号 as FClothNO,'JLT' as PRDGRP,'JLT' as ARTGRP,M.花号 as FColorNO,设计员 as FDesignName"
                +",CAST(日期 as varchar) as FDesignDate,'M  ' as FLengthUnit,CAST(订量 as varchar) as FDeliveLength,CAST(整经长 as varchar) as FGrayLength,"
                +"织机 as FWeavingMachineCode,"
                + "CAST(胚布幅宽 as varchar) as FGrayBreadth_CM,CAST(ROUND(总根数/胚布幅宽,0) as varchar)  as FGrayWarpDensity_Inch,"
                    + "CAST(胚布纬密 as varchar) as FGrayWeftDensity_Inch,CAST(成品幅宽 as varchar) as FFinishedBreadth_CM,CAST(机上纬密 as varchar) as FGrayWeftDensity_Inch,"
                + "CAST(ROUND(总根数/成品幅宽,0) as varchar)   as FFinishedWarpDensity_Inch,CAST(成品纬密 as varchar)  as FFinishedWeftDensity_Inch,"
                + "ISNULL(组织,'')as FWeavingName,ISNULL(布身穿法,'') as FDrawingBody,CAST( len(纬纱支数)-len(replace(纬纱支数,'，','')) as varchar) as FWeftThreadCount,"
                +"CAST(len(经纱支数)-len(replace(经纱支数,'，',''))  as varchar) as FWarpThreadCount, "
                    + "CAST(ISNULL(整经长,'0') as varchar) as FBeamingLength,ISNULL(加工方法,'') as FFinishingDemand,ISNULL(left(加工方法,10),'') as FFinishCode,CAST(总根数 as varchar)  as FTotalEnds, 色纱排列 as WSeq,"
                + "ISNULL(布边排列,'') as SSeq,ISNULL(经纱颜色,'') as WColor,ISNULL(纬纱颜色,'') as FColor,ISNULL(经纱自定KG,'') as WCUsage,ISNULL(经纱代号,'') as WYarn,"
                +"ISNULL(经纱支数,'') as WYCount,"
                + "ISNULL(经纱色号,'') as WYColor,ISNULL(经纱色名,'') as WYCDes,ISNULL(经纱损耗,'') as WUsage,ISNULL(纬纱代号,'') as FYarn,ISNULL(纬纱支数,'') as FYCount,"
                    + "ISNULL(纬纱色号,'') as FYColor,ISNULL(纬纱色名,'') as FYCDes,ISNULL(纬纱损耗,'') as YUsage,ISNULL(纬纱梭序,'') as YSeq,ISNULL(纬纱自定KG,'')as YCUsage,"
                    + "ISNULL( CAST(经纱条数1 as varchar)+','+CAST(经纱条数2 as varchar)+','+CAST(经纱条数3 as varchar)+','+CAST(经纱条数4 as varchar)+','+CAST(经纱条数5 as varchar)+','+CAST(经纱条数6 as varchar)+','+CAST(经纱条数7 as varchar)+','+CAST(经纱条数8 as varchar)+','+CAST(经纱条数9 as varchar)+','+CAST(经纱条数10 as varchar)+','+CAST(经纱条数11 as varchar)+','+CAST(经纱条数12 as varchar)+','+CAST(经纱条数13 as varchar)+','+CAST(经纱条数14 as varchar)+','+CAST(经纱条数15 as varchar),'') as FWarpEnds,"
                    + "ISNULL(CAST(纬纱条数1 as varchar)+','+CAST(纬纱条数2 as varchar)+','+CAST(纬纱条数3 as varchar)+','+CAST(纬纱条数4 as varchar)+','+CAST(纬纱条数5 as varchar)+','+CAST(纬纱条数6 as varchar)+','+CAST(纬纱条数7 as varchar)+','+CAST(纬纱条数8 as varchar),'') as FWeftEnds,"
                + "ISNULL(CAST(经纱用量1 as varchar)+','+CAST(经纱用量2 as varchar)+','+CAST(经纱用量3 as varchar)+','+CAST(经纱用量4 as varchar)+','+CAST(经纱用量5 as varchar)+','+CAST(经纱用量6 as varchar)+','+CAST(经纱用量7 as varchar)+','+CAST(经纱用量8 as varchar)+','+CAST(经纱用量9 as varchar)+','+CAST(经纱用量10 as varchar)+','+CAST(经纱用量11 as varchar)+','+CAST(经纱用量12 as varchar)+','+CAST(经纱用量13 as varchar)+','+CAST(经纱用量14 as varchar)+','+CAST(经纱用量15 as varchar),'') as FWarpUsage,"
                + "ISNULL(CAST(纬纱用量1 as varchar)+','+CAST(纬纱用量2 as varchar)+','+CAST(纬纱用量3 as varchar)+','+CAST(纬纱用量4 as varchar)+','+CAST(纬纱用量5 as varchar)+','+CAST(纬纱用量6 as varchar)+','+CAST(纬纱用量7 as varchar)+','+CAST(纬纱用量8 as varchar),'') as FWeftUsage"
                + " FROM 规格表 M LEFT JOIN 经纬纱 Y ON M.布号=Y.布号"
                + " WHERE rTrim(M.布号) =@FClothNO AND 胚布幅宽>0 AND 成品幅宽>0  ";
                //fKey = fcloth.Trim() + fcolor.Trim();
                fKey = cadkey.Trim();
                sql.Parameters.Add("@FClothNO", fKey);

                SResult = Connect2Proxy(sql);
                if (SResult.Tables.Count > 0)
                {
                    tableLocal = SResult.Tables[0];
                    tableLocal.TableName = "TechMaster";
                    GetFColor(ref SResult);
                    Convert2TechDetail(ref SResult);
                    fail=ConsolidateData(ref SResult);
                    if (!fail)
                    {
                        SReturn.Merge(SResult);
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return SReturn;
        }
        private bool ConsolidateData(ref DataSet src)
        {
            bool fail = false;
            if (src.Tables["TechMaster"].Rows.Count == 0)
            {
                fail = true;
                return fail;
            }
            foreach (DataRow row in src.Tables["TechMaster"].Rows)
            {
                string client = "00";
                string art = row["FClothNO"].ToString();
                string color = row["FColorNO"].ToString();
                DataRow dwData = INTEXDB.VAART.NewRow();
                dwData["VAAMANDANT"]=client;
                dwData["VAAART"]=Left(art+"                     ",24);                  
                DataSet SResult = INTEXDBC.QueryVAART(dwData, 2);
                if (SResult.Tables[0].Rows.Count == 0)
                {
                    fail = true;
                    break;
                }
                foreach (DataRow RX in SResult.Tables[0].Rows)
                {
                    //VAAPRGR VAAARTGRP
                    row["PRDGRP"] = RX["VAAPRGR"];
                    row["ARTGRP"] = RX["VAAARTGRP"];
                }
                dwData = INTEXDB.VAFARBEN.NewRow();
                dwData["VAFMANDANT"] = client;
                dwData["VAFART"] = Left(art + "                     ", 24);
                dwData["VAFFARBE"] = Left(color + "                     ", 10);
                SResult = INTEXDBC.QueryVAFARBEN(dwData, 4);
                if (SResult.Tables[0].Rows.Count == 0)
                {
                    fail = true;
                    break;
                }
                foreach (DataRow RX in SResult.Tables[0].Rows)
                {
                    //VAAPRGR VAAARTGRP
                    row["FFinishCode"] = RX["VAFBESCHICH"];                    
                } 
            }
            return fail;
        }
        public void Convert2TechDetail(ref DataSet src)
        {
            if (src.Tables["TechMaster"].Rows.Count == 0)
                return;
            string[] wYarn = src.Tables["TechMaster"].Rows[0]["WYarn"].ToString().Split(new char[1] { ',' });//CVC451,CVC451,CVC451,CVC451,CVC451,CS40+40D,CS40+40D,CS40+40D,				
            string[] wColor = src.Tables["TechMaster"].Rows[0]["WColor"].ToString().Split(new char[1] { ',' });
            string[] wCDes = src.Tables["TechMaster"].Rows[0]["WYCDes"].ToString().Split(new char[1] { ',' });
            string[] wCount = src.Tables["TechMaster"].Rows[0]["FWarpEnds"].ToString().Split(new char[1] { ',' });
            string[] wUsage = src.Tables["TechMaster"].Rows[0]["FWarpUsage"].ToString().Split(new char[1] { ',' });
            char [] codes=new char[25] { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','Q','R','S','T','U','V','W','X','Y','Z' };
            if (SetCAD == null)
                SetCAD = new SETINTEXDB();
            DataTable tbTechDetail = INTEXDB.TechDetail.Clone();
            int FCharValue = 64;
            int index = 0;
            if (wYarn.Length > 0)
            {
            foreach (string yarn in wYarn)
            {
                if (yarn.Trim() == "")
                    break;
                DataRow rw = tbTechDetail.Rows.Add();
                FCharValue++;
                rw["FCharValue"] = FCharValue;
                rw["FThreadChar"] = codes[index];
                rw["FIsWarp"] = "True";
                rw["Fcoefficient"] = "0";                
                rw["FThreadCode"] = yarn;
                if (wColor.Length > index)
                {
                    rw["FColorCode"] = wColor[index];
                }
                else
                {
                    rw["FColorCode"] = "000000";
                }
                rw["FThreadCountAll"] = wCount[index];
                rw["FThreadDossage"] = wUsage[index];
                rw["FRealThreadDossage"] = wUsage[index];
                index++;
            }
            }
            index = 0;
            FCharValue = 96;
            wYarn = src.Tables["TechMaster"].Rows[0]["FYarn"].ToString().Split(new char[1] { ',' });//CVC451,CVC451,CVC451,CVC451,CVC451,CS40+40D,CS40+40D,CS40+40D,				
            wColor = src.Tables["TechMaster"].Rows[0]["FColor"].ToString().Split(new char[1] { ',' });
            wCDes = src.Tables["TechMaster"].Rows[0]["FYCDes"].ToString().Split(new char[1] { ',' });
            wCount = src.Tables["TechMaster"].Rows[0]["FWeftEnds"].ToString().Split(new char[1] { ',' });
            wUsage = src.Tables["TechMaster"].Rows[0]["FWeftUsage"].ToString().Split(new char[1] { ',' });
            codes = new char[25] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
            if (wYarn.Length > 0)
            {
                foreach (string yarn in wYarn)
                {
                    if (yarn.Trim() == "")
                        break;
                    DataRow rw = tbTechDetail.Rows.Add();
                    FCharValue++;
                    rw["FCharValue"] = FCharValue;
                    rw["FIsWarp"] = "False";
                    rw["FThreadChar"] = codes[index];
                    rw["FThreadCode"] = yarn;
                    rw["Fcoefficient"] = "0";
                    rw["FColorName"] = wCDes[index];
                    if (wColor.Length > index)
                    {
                        rw["FColorCode"] = wColor[index];
                    }
                    else
                    {
                        rw["FColorCode"] = "000000";
                    }
                    rw["FThreadCountAll"] = wCount[index];
                    rw["FThreadDossage"] = wUsage[index];
                    rw["FRealThreadDossage"] = wUsage[index];
                    index++;
                }
            }
            src.Merge(tbTechDetail);
        }
    }
}
